package com.buss.product.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.base.model.Branch;
import com.buss.base.service.BranchService;
import com.buss.core.controller.BaseController;
import com.buss.core.dic.RecordStatus;
import com.buss.core.exception.ServiceException;
import com.buss.core.exception.WebException;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.Pagination;
import com.buss.core.persistence.ResultList;
import com.buss.core.sysparam.SysStaticParam;
import com.buss.core.utils.StringUtil;
import com.buss.product.model.Brand;
import com.buss.product.model.CatePropGroup;
import com.buss.product.model.GoodsCategory;
import com.buss.product.service.BrandService;
import com.buss.product.service.CatePropGroupService;
import com.buss.product.service.GoodsCategoryService;

@Controller
@RequestMapping("/admin/goodscategory")
public class GoodsCategoryController extends BaseController {

	@Autowired
	private GoodsCategoryService categoryService;
	
	@Autowired
	private BranchService branchService;
	
	@Autowired
	private BrandService brandService;
	
	@Autowired
	private CatePropGroupService propGroupService;
	
	@Override
	@RequestMapping("/page")
	public ModelAndView listPage(String menuid) {
		ModelAndView view = new ModelAndView("goodscategory/listpage");
		view.addObject(SysStaticParam._MENUID_NAME, menuid);
		return view;
	}


	@RequestMapping("/{type}")
	public ModelAndView editPage(@PathVariable String type, Long id,HttpServletRequest request) {
		ModelAndView view = new ModelAndView("goodscategory/edit");
		GoodsCategory category = new GoodsCategory();
		GoodsCategory parentCategory = null;		
		String branchName = "";
		if(EDIT_PAGE.equals(type)){
			category = categoryService.loadCategory(id);
			branchName = getBranchName(category,request);
			if(category.getParentId() != 0){
				parentCategory = categoryService.loadCategory(category.getParentId());
			}else{
				parentCategory = new GoodsCategory();
				parentCategory.setId(0L);
				parentCategory.setName("顶级分类");
			}
		}else{			
			category.setStatus(RecordStatus.normal);			
			if(id != 0){
				parentCategory = categoryService.loadCategory(id);
			}
			if(parentCategory == null){	
				category.setBranchId("0");
				branchName = "公用分类";
				parentCategory = new GoodsCategory();
				parentCategory.setId(0L);
				parentCategory.setName("顶级分类");
			}else{
				category.setBranchId(parentCategory.getBranchId());
				branchName = getBranchName(parentCategory,request);
			}
		}
		view.addObject("branchName",branchName);
		view.addObject("type", type);
		view.addObject("category", category);
		view.addObject("parentCategory", parentCategory);
		return view;
	}

	@Override
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(Long[] ids) throws WebException {
		categoryService.removeCategory(ids);
		return SysStaticParam.resultMessage("删除商品分类信息成功!");
	}

	/**
	 * 新增商品分类信息
	 * @param category
	 * @param request
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String,Object> add( GoodsCategory category,HttpServletRequest request) throws WebException{
		category.setCompanyId(getCompanyId(request));
		if(StringUtil.isEmpty(category.getBranchId())){
			category.setBranchId("," + getBranchId(request).toString() + ",");
		}
		try {
		   category = categoryService.saveCategory(category);
		} catch (ServiceException e) {
			throw new WebException(e.getMessage());
		}
		Map<String, Object> map = SysStaticParam.resultMessage("新增商品分类成功!");
		map.put("category", category);
		return map;
	}
	
	/**
	 * 修改商品分类信息
	 * @param category
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String,Object> edit( GoodsCategory category,HttpServletRequest request){
		category.setCompanyId(getCompanyId(request));
		if(StringUtil.isEmpty(category.getBranchId())){
			category.setBranchId("," + getBranchId(request).toString() + ",");
		}
		categoryService.editCategory(category);
		return SysStaticParam.resultMessage("修改商品分类成功!");
	}
	
	/**
	 * 获取商品分类信息列表
	 * @param parentId
	 * @param name
	 * @param status
	 * @param propGroupId
	 * @param orderField
	 * @param orderType
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Map<String,Object> list(Long parentId,String name,RecordStatus status,Long propGroupId,
			String orderField,String orderType,Boolean isPage, Pagination page,HttpServletRequest request){
		OrderBy orderBy = null;
		if(StringUtil.isNotEmpty(orderField)){
			orderBy = new OrderBy();
			orderBy.add(orderField, orderType);
		}
		if(isPage != null && !isPage){
			page = null;
		}
		ResultList<GoodsCategory> rs = categoryService.queryCategory(getCompanyId(request), getBranchId(request).toString(), parentId, name, status, propGroupId, orderBy, page);
		Map<String, Object> map = SysStaticParam.resultMessage("获取商品分类信息成功!");
		map.put(SysStaticParam._RESULT, rs);		
		return map;
	}
	
	@RequestMapping("/brandpage")
	public ModelAndView editBrandPage(Long categoryId,HttpServletRequest request){
		ModelAndView view = new ModelAndView("/goodscategory/category_brand");
		List<Brand> unSelBrands = brandService.queryBrandNotInCategoryId(categoryId).getData();
		List<Brand> selBrands = brandService.queryBrand(categoryId).getData();		
		view.addObject("categoryId", categoryId);
		view.addObject("unSelBrands", unSelBrands);
		view.addObject("selBrands", selBrands);
		return view;
	}
	
	@RequestMapping("/propgrouppage")
	public ModelAndView editPropGroupPage(Long categoryId,HttpServletRequest request){
		ModelAndView view = new ModelAndView("/goodscategory/category_propgroup");
		List<CatePropGroup> unSelectGroups = propGroupService.queryCatePropGroupNotByParentCategoryId(getCompanyId(request), categoryId, RecordStatus.normal, null, null).getData();
		List<CatePropGroup> selectGroups = propGroupService.queryCatePropGroupByParentCategoryId(getCompanyId(request), categoryId, RecordStatus.normal, null, null).getData();
		view.addObject("categoryId", categoryId);
		view.addObject("unSelGroups", unSelectGroups);
		view.addObject("selGroups", selectGroups);		
		return view;
	}
	
	/**
	 * 保存商品分类和品牌对应关系
	 * @param categoryId
	 * @param brandIds
	 * @return
	 */
	@RequestMapping("/updatecategorybrand/{categoryId}")
	@ResponseBody
	public Map<String,Object> updateCategoryBrand(@PathVariable Long categoryId,Long[] brandIds){
		categoryService.updateCategoryBrand(categoryId, brandIds);
		return SysStaticParam.resultMessage("保存商品分类和品牌对应关系成功!");
	}
	
	/**
	 * 保存商品分类和属性分组对应关系
	 * @param categoryId
	 * @param brandIds
	 * @return
	 */
	@RequestMapping("/updatecategorygroup/{categoryId}")
	@ResponseBody
	public Map<String,Object> updateCategoryGroup(@PathVariable Long categoryId,Long[] groupIds){
		categoryService.updateCategoryPropGroup(categoryId, groupIds);
		return SysStaticParam.resultMessage("保存商品分类和属性分组对应关系成功!");
	}
	
	/**
	 * 获取店铺名称
	 * @param category
	 * @param isPub
	 * @param request
	 * @return
	 */
	private String getBranchName(GoodsCategory category,HttpServletRequest request){
		String branchName = "";
		if(category.getBranchId().equals("0")){
			branchName = "公用分类";
		}else if(category.getBranchId().equals("," + getBranchId(request) + ",")){
			branchName = "本店铺私有";
		}else{
			String branchId = category.getBranchId();
			branchId = branchId.substring(1, branchId.length() - 1);
			String[] tmps = branchId.split(",");
			Long[] branchIds = new Long[tmps.length];
			for(int i = 0;i < tmps.length - 1;i++){
				branchIds[i] = new Long(tmps[i]);
			}
			ResultList<Branch> rs = branchService.queryBranch(getCompanyId(request), branchIds);
			for(Branch branch : rs.getData()){
				branchName += branch.getName() + ",";
			}
			branchName = branchName.substring(0, branchName.length() - 1);
		}
		return branchName;
	}
	
	@Override
	public ModelAndView editPage(String type, Long id) {
		// TODO Auto-generated method stub
		return null;
	}
}
